package com.example.zhixu.myapp2;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.view.View;

import java.io.IOException;

public class MusicService extends Service {
    private MediaPlayer player;
    private String MusicPath;
    private Boolean isPause = false;

    public MusicService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        MusicPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Music/";
        Log.i("zhixu", MusicPath);
        player = new MediaPlayer();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent.getStringExtra("action");
        switch (action) {
            case "play":
                try {
                    play();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case "pause":
                pause();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void play () throws IOException {
        if (!isPause) {
            player.reset();
            player.setDataSource(MusicPath + "Monody.mp3");
            player.prepare();
        }
        player.start();
        isPause = false;
    }

    private void pause() {
        player.pause();
        isPause = true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        player.stop();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}
